<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>A股上证指数量化交易系统</title>
    <script src="/static/echarts.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .chart-container {
            height: 500px;
            margin-bottom: 30px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }
        .control-group {
            margin-bottom: 10px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, select {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .stats {
            display: flex;
            justify-content: space-around;
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .stat-item {
            text-align: center;
            min-width: 120px;
            margin: 5px;
        }
        .stat-value {
            font-size: 1.5em;
            font-weight: bold;
            color: #007bff;
        }
        .stat-label {
            font-size: 0.9em;
            color: #666;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            text-align: center;
            padding: 20px;
            color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>A股上证指数量化交易系统</h1>
        
        <div class="stats" id="stats">
            <div class="stat-item">
                <div class="stat-value" id="initial-capital">¥10,000</div>
                <div class="stat-label">初始资金</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" id="final-asset">¥0</div>
                <div class="stat-label">最终资产</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" id="total-return">0%</div>
                <div class="stat-label">总收益率</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" id="signal-count">0</div>
                <div class="stat-label">交易信号数</div>
            </div>
        </div>
        
        <div class="controls">
            <div class="control-group">
                <label for="short-window">短期均线周期:</label>
                <input type="number" id="short-window" min="2" max="50" value="5">
            </div>
            <div class="control-group">
                <label for="long-window">长期均线周期:</label>
                <input type="number" id="long-window" min="5" max="100" value="20">
            </div>
            <div class="control-group">
                <label for="start-date">开始日期:</label>
                <input type="date" id="start-date" value="2020-01-01">
            </div>
            <div class="control-group">
                <label for="end-date">结束日期:</label>
                <input type="date" id="end-date" value="2023-12-31">
            </div>
            <div class="control-group">
                <button id="update-button">更新图表</button>
            </div>
        </div>
        
        <div id="chart" class="chart-container">
            <div class="loading" id="loading">正在加载数据...</div>
        </div>
        
        <div class="controls">
            <div class="control-group">
                <label for="strategy-type">策略类型:</label>
                <select id="strategy-type">
                    <option value="ma">双均线策略</option>
                </select>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        var chart;
        
        // DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化图表
            initializeChart();
            
            // 绑定按钮事件
            bindEvents();
            
            // 首次加载数据
            updateChart();
        });
        
        // 初始化图表
        function initializeChart() {
            var chartElement = document.getElementById('chart');
            if (chartElement) {
                chart = echarts.init(chartElement);
            } else {
                console.error('图表容器元素未找到');
            }
        }
        
        // 绑定事件
        function bindEvents() {
            var updateButton = document.getElementById('update-button');
            if (updateButton) {
                updateButton.addEventListener('click', updateChart);
            } else {
                console.error('更新按钮未找到');
            }
        }
        
        // 更新图表函数
        function updateChart() {
            // 检查必要的DOM元素是否存在
            var loadingElement = document.getElementById('loading');
            var chartElement = document.getElementById('chart');
            
            // 显示加载状态
            if (loadingElement) {
                loadingElement.style.display = 'block';
                loadingElement.textContent = '正在加载数据...';
            }
            
            if (chart) {
                chart.clear();
            }
            
            // 获取参数
            var shortWindowElement = document.getElementById('short-window');
            var longWindowElement = document.getElementById('long-window');
            var startDateElement = document.getElementById('start-date');
            var endDateElement = document.getElementById('end-date');
            
            if (!shortWindowElement || !longWindowElement || !startDateElement || !endDateElement) {
                console.error('必要的输入元素未找到');
                if (loadingElement) {
                    loadingElement.textContent = '页面元素加载失败，请刷新页面重试';
                }
                return;
            }
            
            var shortWindow = shortWindowElement.value;
            var longWindow = longWindowElement.value;
            var startDate = startDateElement.value.replace(/-/g, '');
            var endDate = endDateElement.value.replace(/-/g, '');
            
            // 构造API URL (使用相对路径，避免端口问题)
            var apiUrl = '/api/stock_data/' + startDate + '/' + endDate + '/' + shortWindow + '/' + longWindow;
            
            // 获取数据
            fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    // 检查是否有错误
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    // 隐藏加载状态
                    if (loadingElement) {
                        loadingElement.style.display = 'none';
                    }
                    
                    // 更新统计数据
                    updateStats(data.stats);
                    
                    // 更新图表
                    updateChartDisplay(data);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    handleError(error.message);
                });
        }
        
        // 更新统计数据
        function updateStats(stats) {
            var initialCapitalElement = document.getElementById('initial-capital');
            var finalAssetElement = document.getElementById('final-asset');
            var totalReturnElement = document.getElementById('total-return');
            var signalCountElement = document.getElementById('signal-count');
            
            if (initialCapitalElement && stats.initial_capital) {
                initialCapitalElement.textContent = '¥' + stats.initial_capital.toLocaleString();
            }
            
            if (finalAssetElement && stats.final_asset) {
                finalAssetElement.textContent = '¥' + stats.final_asset.toLocaleString(undefined, {maximumFractionDigits: 2});
            }
            
            if (totalReturnElement && stats.total_return !== undefined) {
                totalReturnElement.textContent = stats.total_return.toFixed(2) + '%';
                
                // 设置收益率颜色
                if (stats.total_return >= 0) {
                    totalReturnElement.style.color = '#28a745';
                } else {
                    totalReturnElement.style.color = '#dc3545';
                }
            }
            
            if (signalCountElement && stats.total_signals !== undefined) {
                signalCountElement.textContent = stats.total_signals;
            }
        }
        
        // 更新图表显示
        function updateChartDisplay(data) {
            if (!chart) {
                console.error('图表实例未初始化');
                return;
            }
            
            // 准备买入信号数据
            var buySignals = data.buy_signals.map(signal => {
                return {
                    name: '买入信号',
                    xAxis: signal.date,
                    yAxis: signal.price
                };
            });
            
            // 准备卖出信号数据
            var sellSignals = data.sell_signals.map(signal => {
                return {
                    name: '卖出信号',
                    xAxis: signal.date,
                    yAxis: signal.price
                };
            });
            
            // 配置图表选项
            var option = {
                title: {
                    text: '上证指数与交易信号'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['收盘价', '短期均线', '长期均线', '买入信号', '卖出信号']
                },
                xAxis: {
                    type: 'category',
                    data: data.dates
                },
                yAxis: {
                    type: 'value',
                    scale: true
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        start: 0,
                        end: 100
                    }
                ],
                series: [
                    {
                        name: '收盘价',
                        type: 'line',
                        data: data.closes,
                        smooth: true,
                        lineStyle: {
                            color: '#333'
                        }
                    },
                    {
                        name: '短期均线',
                        type: 'line',
                        data: data.short_ma,
                        smooth: true,
                        lineStyle: {
                            color: '#007bff'
                        }
                    },
                    {
                        name: '长期均线',
                        type: 'line',
                        data: data.long_ma,
                        smooth: true,
                        lineStyle: {
                            color: '#28a745'
                        }
                    },
                    {
                        name: '买入信号',
                        type: 'scatter',
                        data: buySignals,
                        symbol: 'triangle',
                        symbolSize: 15,
                        itemStyle: {
                            color: '#28a745'
                        }
                    },
                    {
                        name: '卖出信号',
                        type: 'scatter',
                        data: sellSignals,
                        symbol: 'triangle',
                        symbolRotate: 180,
                        symbolSize: 15,
                        itemStyle: {
                            color: '#dc3545'
                        }
                    }
                ]
            };
            
            // 使用配置项显示图表
            chart.setOption(option, true);
        }
        
        // 处理错误
        function handleError(errorMessage) {
            var loadingElement = document.getElementById('loading');
            var chartElement = document.getElementById('chart');
            
            if (loadingElement) {
                loadingElement.style.display = 'none';
            }
            
            if (chartElement) {
                chartElement.innerHTML = '<div class="error">数据加载失败: ' + errorMessage + '</div>';
            }
        }
        
        // 窗口大小改变时重置图表大小
        window.addEventListener('resize', function() {
            if (chart) {
                chart.resize();
            }
        });
    </script>
</body>
</html>